package com.panfeng.xcloud.boss.provider.member.service.impl;

import com.google.common.base.Joiner;
import com.panfeng.xcloud.boss.provider.member.security.auth.SecurityUtils;
import com.panfeng.xcloud.boss.provider.member.service.IPermissionService;
import com.panfeng.xcloud.common.core.constants.Constants;
import com.panfeng.xcloud.common.core.constants.GlobalConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 *
 * 用户权限业务service
 *
 * @author xiaobo
 * @version 1.0
 * @since 2019-08-13
 */
@Component("permissionService")
@Slf4j
public class PermissionServiceImpl implements IPermissionService {

	private AntPathMatcher antPathMatcher = new AntPathMatcher();
	private static final String OAUTH2_CLIENT_PREFIX = "xdcloud-client-";

	@Resource
	private ClientDetailsService clientDetailsService;

	@Override
	public boolean hasPermission(Authentication authentication, HttpServletRequest request) {
		String mobileNo = SecurityUtils.getCurrentLoginName();
		Set<String> currentAuthoritySet = SecurityUtils.getCurrentAuthoritys();
		String requestURI = request.getRequestURI();
		log.info(">>> 验证权限mobileNo={}, requestURI={}, hasAuthoritys={}", mobileNo, requestURI, Joiner.on(GlobalConstant.Symbol.COMMA).join(currentAuthoritySet));
		//IOS appStore 审核账号放开权限
		if (StringUtils.equals(mobileNo, Constants.TEST_ACCOUT_USER_PHONE)) {
			return true;
		}
		//验证feign客户端之间调用
		if (mobileNo.contains(OAUTH2_CLIENT_PREFIX)) {
			ClientDetails clientDetails = clientDetailsService.loadClientByClientId(mobileNo);
			return clientDetails != null;
		}
		//authority可能是某个角色名也可以是url资源权限
		for (final String authority : currentAuthoritySet) {
			if (StringUtils.equals(authority, "USER_ROLE")) {
				log.info(">>> 命中角色权限{} <<<<",authority);
				return true;
			}
			if (antPathMatcher.match(authority, requestURI)) {
				log.info(">>> 命中url资源权限{} <<<<",authority);
				return true;
			}
		}
		return false;
	}
}
